// 路由守卫
import router from '@/router'
import store from '@/store'
import nprogress from 'nprogress' // 引入进度条
import 'nprogress/nprogress.css'

// 白名单
const whiteList = ['/login', '/404']

// 前置守卫
router.beforeEach(async(to, from, next) => {
  nprogress.start() // 开启进度条
  if (store.getters.token) {
    // 要访问登录页
    if (to.path === '/login') {
      next('/') // 跳转主页
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const routes = await store.dispatch('permission/filterRoutes', roles.menus)
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
        // 如果进行了addRoutes()必须用next(to.path)，否则会导致刷新路由失效
      } else {
        next() // 放行
      }
    }
  } else {
    // 地址在白名单
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
  nprogress.done() // 解决手动切换地址时，进度条不关闭问题
})

// 后置守卫
router.afterEach(() => {
  nprogress.done() // 关闭进度条
})
